#include "sock.h"
#include <fstream>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>


#define WWWROOT "./wwwroot/"
#define HOME_PAGE "index.html"

void Usage(char *args)
{
  std::cout << "Usage\n\t" << args << " server.port" << std::endl;
}

void *Service_run(void *args)
{
  int sock = *(int *)args;
  //delete (int *)args;
  pthread_detach(pthread_self());
  char buffer[1024 * 10];
  ssize_t size = recv(sock, buffer, sizeof(buffer), 0);
  if (size > 0)
  {
    // std::string http_response = "http/1.1 200 OK\n";
    // http_response += "Content-Type: text/plain\n";
    // http_response += "\n";
    // http_response += "xiang ge xi huan s an shang you ya\n";
    // send(sock, http_response.c_str(), http_response.size(), 0);

    // std::cout << buffer;
    std::string html_file = WWWROOT;
    html_file += HOME_PAGE;
    struct stat st;
    stat(html_file.c_str(), &st);

    std::string http_response = "http/1.1 200 ok\n";
    http_response += "Content-Type: text/html; charset=utf8\n";
    http_response += "Content-Length: ";
    http_response += std::to_string(st.st_size);
    http_response += "\n";
    http_response += "\n";
    //正文
    std::ifstream in(html_file);
    if (!in.is_open()){
      std::cerr << "html_file open failed" << errno << std::endl; 
    }
    else 
    {
      std::cout << "file read begin" <<std::endl;
      std::string content;
      std::string line;
      while (std::getline(in, line)){
        content += line;
      }
      http_response += content;
      in.close();
      std::cout << "file read end" << std::endl;
      send(sock, http_response.c_str(), http_response.size(), 0);
    }
  }
  close(sock);
  return nullptr;
}

int main(int argc, char *argv[])
{
  if (argc != 2)
  {
    Usage(argv[0]);
  }
  uint16_t ser_port = atoi(argv[1]);

  int sock = Sock::sock();
  Sock::Bind(sock, ser_port);
  Sock::Listen(sock);
  while (true)
  {
    int new_sock = Sock::Accept(sock);
    if (new_sock > 0)
    {
      pthread_t tid;
      //int *parm = new int(new_sock);
      pthread_create(&tid, nullptr, Service_run, (void *)&new_sock);
      sleep(1);
    }
  }
}
